import webapp2
import jinja2
import os
from google.appengine.api import users
import logging
import era
import country

import spreadsheet
from google.appengine.ext import ndb
import dic
import geo
import labelcat



jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))



class AdminPage(webapp2.RequestHandler):
    def get(self):
        template_values = {
        }  
        template = jinja_environment.get_template("gameadmin.html")
        self.response.out.write(template.render(template_values))
        
class InitDic(webapp2.RequestHandler):
    def post(self):
        lang = str(self.request.get("lang"))
        cat = self.request.get("cat")
        logging.info("lang="+lang+",cat="+cat)
        spreadsheet_operation = spreadsheet.Operation()
        spreadsheet_feed = spreadsheet_operation.getFeed();
        gd_client = spreadsheet_operation.gd_client;
        # clean data
        dictionaries = dic.Dic.query(dic.Dic.lang == lang,dic.Dic.cat==cat)
        for dictionary_element in dictionaries:
            dictionary_element.key.delete()
    
        for i, spreadsheet_entry in enumerate(spreadsheet_feed.entry):
            spreadsheet_title = spreadsheet_entry.title.text
            
            if "UDATA-LABEL-" + lang.upper() == spreadsheet_title :
                spreadsheet_id_parts = spreadsheet_entry.id.text.split('/')
                spreadsheet_id = spreadsheet_id_parts[len(spreadsheet_id_parts) - 1]                
                worksheet_feed = gd_client.GetWorksheetsFeed(spreadsheet_id);
                for j, worksheet_entry in enumerate(worksheet_feed.entry):
                    dic_cat = worksheet_entry.title.text
                    if dic_cat == cat:
                        worksheet_id_parts = worksheet_entry.id.text.split('/')
                        worksheet_id = worksheet_id_parts[len(worksheet_id_parts) - 1]                  
                        logging.info("category:" + dic_cat)
                        list_feed = gd_client.GetListFeed(spreadsheet_id, worksheet_id)
                        for  k, list_entry in enumerate(list_feed.entry):
                            dic_name = list_entry.custom["name"].text  
                            dic_label = list_entry.custom["label"].text
                            dic_entity = dic.Dic(name=dic_name, lang=lang, label=dic_label, cat=dic_cat)
                            dic_entity.put()
        self.redirect("/game/admin")

